from flask import Flask, request, jsonify
from src.db.operations import (
    register_user, get_user_by_username, authenticate_user,
    create_artwork, get_all_artworks, get_artworks_filtered,
    get_artwork_by_id, add_collection, remove_collection,
    get_user_collections, is_artwork_collected, create_transaction,
    update_transaction_status, get_user_transactions, get_transaction_detail,
    add_traceability_info, get_artwork_trace
)
import logging
from functools import wraps

# 初始化Flask应用
app = Flask(__name__)

# 日志配置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 允许跨域请求的前端地址（与前端Live Server地址一致）
FRONTEND_ORIGIN = "http://127.0.0.1:5500"

# 跨域请求处理（全局拦截器）
@app.after_request
def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = FRONTEND_ORIGIN
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
    response.headers['Access-Control-Allow-Credentials'] = 'true'  # 允许跨域携带Cookie
    return response


# 登录验证装饰器（保护需要登录的接口）
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        # 从请求中获取用户名（实际项目中应从Token或Session获取）
        username = request.json.get('username') if request.method == 'POST' else request.args.get('username')
        if not username or not get_user_by_username(username):
            return jsonify({"success": False, "error": "请先登录"}), 401
        return f(*args, **kwargs)
    return decorated_function

# 1. 用户注册接口
@app.route("/register", methods=["POST"])
def register():
    try:
        data = request.json
        # 验证必填字段
        required_fields = ["username", "password", "real_name", "contact_info", "user_role"]
        if not all(field in data for field in required_fields):
            return jsonify({"success": False, "error": "缺少必填字段"}), 400

        # 调用注册函数
        success = register_user(
            username=data["username"],
            password=data["password"],
            real_name=data["real_name"],
            contact_info=data["contact_info"],
            address=data.get("address", ""),  # 地址可选
            user_role=data["user_role"]
        )

        if success:
            return jsonify({"success": True, "message": "注册成功"})
        else:
            return jsonify({"success": False, "error": "用户名已存在"}), 400
    except Exception as e:
        logger.error(f"注册接口错误：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

# 2. 用户登录接口
@app.route("/login", methods=["POST"])
def login():
    try:
        data = request.json
        if not all(k in data for k in ["username", "password"]):
            return jsonify({"authenticated": False, "error": "缺少用户名或密码"}), 400

        # 验证用户名和密码
        authenticated = authenticate_user(data["username"], data["password"])
        if authenticated:
            # 获取用户信息（不含密码）
            user = get_user_by_username(data["username"])
            user.pop("password")  # 移除密码字段
            return jsonify({
                "authenticated": True,
                "user_info": user
            })
        else:
            return jsonify({"authenticated": False, "error": "用户名或密码错误"}), 401
    except Exception as e:
        logger.error(f"登录接口错误：{str(e)}")
        return jsonify({"authenticated": False, "error": "服务器内部错误"}), 500

# 3. 艺术品相关接口
@app.route("/artworks", methods=["GET"])
def get_artworks():
    """获取所有艺术品（首页展示）"""
    try:
        artworks = get_all_artworks()
        return jsonify({"success": True, "artworks": artworks})
    except Exception as e:
        logger.error(f"获取艺术品列表错误：{str(e)}")
        return jsonify({"success": False, "error": "获取艺术品失败"}), 500

@app.route("/artworks/filter", methods=["GET"])
def filter_artworks():
    """艺术品筛选接口（按关键词、价格区间）"""
    try:
        # 从URL参数获取筛选条件
        keyword = request.args.get('keyword', '').strip()
        min_price = request.args.get('min_price')
        max_price = request.args.get('max_price')
        
        # 转换价格为数字（处理空值和非数字情况）
        try:
            min_price = float(min_price) if min_price else None
            max_price = float(max_price) if max_price else None
        except ValueError:
            return jsonify({"success": False, "error": "价格格式错误"}), 400
        
        # 调用筛选函数
        artworks = get_artworks_filtered(
            keyword=keyword,
            min_price=min_price,
            max_price=max_price
        )
        
        return jsonify({
            'success': True,
            'artworks': artworks
        })
    except Exception as e:
        logger.error(f"筛选艺术品错误: {str(e)}")
        return jsonify({
            'success': False,
            'error': '筛选失败，请稍后再试'
        }), 500

@app.route("/artworks/<int:artwork_id>", methods=["GET"])
def get_artwork_detail(artwork_id):
    """获取单个艺术品详情"""
    try:
        artwork = get_artwork_by_id(artwork_id)
        if artwork:
            return jsonify({"success": True, "artwork": artwork})
        else:
            return jsonify({"success": False, "error": "艺术品不存在"}), 404
    except Exception as e:
        logger.error(f"获取艺术品详情错误：{str(e)}")
        return jsonify({"success": False, "error": "获取详情失败"}), 500

@app.route("/artworks", methods=["POST"])
@login_required
def add_artwork():
    """发布新艺术品（卖家功能）"""
    try:
        data = request.json
        required_fields = ["title", "description", "price", "creator", "owner_id"]
        if not all(field in data for field in required_fields):
            return jsonify({"success": False, "error": "缺少必填字段"}), 400

        artwork_id = create_artwork(
            title=data["title"],
            description=data["description"],
            price=data["price"],
            creator=data["creator"],
            owner_id=data["owner_id"]
        )

        if artwork_id:
            return jsonify({"success": True, "artwork_id": artwork_id})
        else:
            return jsonify({"success": False, "error": "发布艺术品失败"}), 500
    except Exception as e:
        logger.error(f"发布艺术品错误：{str(e)}")
        return jsonify({"success": False, "error": "服务器内部错误"}), 500

# 4. 收藏相关接口
@app.route("/collections/add", methods=["POST"])
@login_required
def add_to_collection():
    """添加收藏"""
    try:
        data = request.json
        if not all(k in data for k in ["user_id", "artwork_id"]):
            return jsonify({"success": False, "error": "缺少用户ID或艺术品ID"}), 400

        success, msg = add_collection(data["user_id"], data["artwork_id"])
        return jsonify({"success": success, "message": msg})
    except Exception as e:
        logger.error(f"添加收藏错误：{str(e)}")
        return jsonify({"success": False, "error": "操作失败"}), 500

@app.route("/collections/remove", methods=["POST"])
@login_required
def remove_from_collection():
    """取消收藏"""
    try:
        data = request.json
        if not all(k in data for k in ["user_id", "artwork_id"]):
            return jsonify({"success": False, "error": "缺少用户ID或艺术品ID"}), 400

        success, msg = remove_collection(data["user_id"], data["artwork_id"])
        return jsonify({"success": success, "message": msg})
    except Exception as e:
        logger.error(f"取消收藏错误：{str(e)}")
        return jsonify({"success": False, "error": "操作失败"}), 500

@app.route("/collections/<int:user_id>", methods=["GET"])
@login_required
def get_collections(user_id):
    """获取用户收藏列表"""
    try:
        collections = get_user_collections(user_id)
        return jsonify({"success": True, "collections": collections})
    except Exception as e:
        logger.error(f"获取收藏列表错误：{str(e)}")
        return jsonify({"success": False, "error": "获取失败"}), 500

# 5. 交易相关接口
@app.route("/transactions/create", methods=["POST"])
@login_required
def create_order():
    """创建交易订单"""
    try:
        data = request.json
        required_fields = ["buyer_id", "seller_id", "artwork_id", "transaction_price"]
        if not all(k in data for k in required_fields):
            return jsonify({"success": False, "error": "缺少交易必要信息"}), 400

        trans_id, msg = create_transaction(
            buyer_id=data["buyer_id"],
            seller_id=data["seller_id"],
            artwork_id=data["artwork_id"],
            transaction_price=data["transaction_price"],
            transaction_location=data.get("transaction_location")
        )

        if trans_id:
            return jsonify({"success": True, "transaction_id": trans_id, "message": msg})
        else:
            return jsonify({"success": False, "error": msg}), 400
    except Exception as e:
        logger.error(f"创建订单错误：{str(e)}")
        return jsonify({"success": False, "error": "创建订单失败"}), 500

@app.route("/transactions/status", methods=["POST"])
@login_required
def update_order_status():
    """更新交易状态（付款/取消/确认收货）"""
    try:
        data = request.json
        if not all(k in data for k in ["transaction_id", "status"]):
            return jsonify({"success": False, "error": "缺少交易ID或状态"}), 400

        success, msg = update_transaction_status(data["transaction_id"], data["status"])
        return jsonify({"success": success, "message": msg})
    except Exception as e:
        logger.error(f"更新交易状态错误：{str(e)}")
        return jsonify({"success": False, "error": "操作失败"}), 500

@app.route("/transactions/<int:user_id>", methods=["GET"])
@login_required
def get_user_orders(user_id):
    """获取用户交易列表"""
    try:
        status = request.args.get("status")
        transactions, msg = get_user_transactions(user_id, status)
        return jsonify({"success": True, "transactions": transactions, "message": msg})
    except Exception as e:
        logger.error(f"获取交易列表错误：{str(e)}")
        return jsonify({"success": False, "error": "获取失败"}), 500

# 6. 溯源相关接口
@app.route("/traceability/<int:artwork_id>", methods=["GET"])
def get_artwork_traceability(artwork_id):
    """获取艺术品溯源记录"""
    try:
        trace_records, msg = get_artwork_trace(artwork_id)
        return jsonify({"success": True, "trace_records": trace_records, "message": msg})
    except Exception as e:
        logger.error(f"获取溯源记录错误：{str(e)}")
        return jsonify({"success": False, "error": "获取失败"}), 500

# 全局错误处理
@app.errorhandler(404)
def handle_404(error):
    return jsonify({
        'success': False,
        'error': '请求的接口不存在'
    }), 404

@app.errorhandler(500)
def handle_500(error):
    logger.error(f"服务器内部错误: {str(error)}")
    return jsonify({
        'success': False,
        'error': '服务器内部错误，请稍后再试'
    }), 500

@app.errorhandler(405)
def handle_405(error):
    return jsonify({
        'success': False,
        'error': '请求方法不支持'
    }), 405

# 启动服务器
if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=5000)
    